import 'dart:ui';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:image_picker_saver/image_picker_saver.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<WebShareState> buildEffect() {
  return combineEffects(<Object, Effect<WebShareState>>{
    WebShareAction.onDone: _onDone,
    WebShareAction.onShare: _onShare,
    WebShareAction.onSnap: _onSnap,
  });
}

void _onDone(Action action, Context<WebShareState> ctx) {
  Navigator.of(ctx.context).pop(ctx.state.done);
}

void _onShare(Action action, Context<WebShareState> ctx) async {
  final String select = await Util.showShareDialog(ctx.context);

  var title = ctx.state.title;
  var desc = "AI老师给你作文意想不到的精批细改！";
  var url = ctx.state.url;
  var image = "assets://assets/images/ic_launcher.png";

  if (url.contains('?')) {
    url += "&ticket=wxShare";
  }
  if (select == 'session') {
    fluwx.share(fluwx.WeChatShareWebPageModel(
        title: title,
        description: desc,
        scene: fluwx.WeChatScene.SESSION,
        webPage: url,
        thumbnail: image));
  } else if (select == 'timeline') {
    fluwx.share(fluwx.WeChatShareWebPageModel(
        title: title,
        description: desc,
        scene: fluwx.WeChatScene.TIMELINE,
        webPage: url,
        thumbnail: image));
  }
}

void _onSnap(Action action, Context<WebShareState> ctx) async {
  var byteData = await ctx.state.controller.takeScreenshot();
  var filePath = await ImagePickerSaver.saveFile(fileData: byteData);
  Util.alert('图片已保存到相册', ctx.context);
}
